<template>
  <div>
    <el-dialog id="attachment" :visible.sync="show" width="950px" class="closeIcon" :title="$t(title)"
      :append-to-body="true" @close="close">
      <div class="top-flex">
        <div class="left">
          <el-button :class="num > 0 ? 'dele' : ''" :disabled="num > 0 ? false : true" size="small"
            style="margin-right: 10px" @click="dele">
            {{ $t('删除附件') }}
          </el-button>
          <el-upload :headers="myHeaders" class="attachment_upload"
            :action="$store.getters.updateURL + 'attachment/uploadAndSave'" :show-file-list="false"
            :on-success="handleSuccess" :on-progress="onProgress" :before-upload="beforeUpload" :data="uploadData">
            <el-button plain @click="getTypeCate">
              {{ $t('上传附件') }}
            </el-button>
          </el-upload>
          <el-button plain @click="showDialog = true">
            {{ $t('网络附件') }}
          </el-button>
          <el-dialog id="attachment" :visible.sync="showDialog" width="950px" class="closeIcon" :title="$t('添加网络附件')"
            :append-to-body="true">
            <el-form ref="urlForm" :model="urlForm" :rules="urlRules" label-width="60px">
              <el-form-item :label="`${$t('名称')}:`" prop="name">
                <el-input v-model="urlForm.name" />
              </el-form-item>
              <el-form-item :label="`${$t('地址')}:`" prop="url">
                <el-input v-model="urlForm.url" />
              </el-form-item>
              <el-form-item :label="`${$t('描述')}:`">
                <el-input v-model="urlForm.description" type="textarea" />
              </el-form-item>
              <div class="btn">
                <el-button @click="showDialog = false">
                  {{ $t('取消') }}
                </el-button>
                <el-button type="primary" @click="uploadUrl">
                  {{ $t('确定') }}
                </el-button>
              </div>
            </el-form>
          </el-dialog>
        </div>
        <el-badge :value="num" :hidden="num > 0 ? false : true">
          <el-button :class="num > 0 ? 'orange' : ''" :type="num > 0 ? 'primary' : ''" :disabled="num > 0 ? false : true"
            size="small" @click="choose">
            {{ $t('使用选中附件') }}
          </el-button>
        </el-badge>
      </div>
      <div class="content">
        <div class="left">
          <InputSearch @search="searchCate" />
          <div id="attachmentCate">
            <el-scrollbar>
              <el-tree ref="tree" class="filter-tree" :data="treeData" :props="defaultProps" highlight-current
                :expand-on-click-node="showTree" :indent="12" node-key="id" :current-node-key="currentNode"
                :default-expanded-keys="defaultExpandKeys" @node-click="handleNodeClick">
                <template slot-scope="{ node, data }">
                  <div class="flex-row treeSortList">
                    <span class="tooltip-wrap">{{ node.label }}</span>
                    <div v-if="showBtn[data.id]" class="doBtn">
                      <el-button v-if="showAdd" type="text" size="mini" :title="$t('添加')" icon="el-icon-plus"
                        @click.stop="() => append(data)" />
                      <el-button v-if="showEdit" type="text" size="mini" :title="$t('编辑')" icon="el-icon-edit-outline"
                        @click.stop="() => edit(data, node)" />
                      <el-button v-if="showDele" type="text" size="mini" :title="$t('删除')" icon="el-icon-delete"
                        @click.stop="() => remove(data, node)" />
                    </div>
                  </div>
                </template>
              </el-tree>
            </el-scrollbar>

            <BaseDialog :title="cate_id == '' ? $t('增加分类') : $t('编辑分类')" :dialog-show.sync="dialogShow2" width="60%"
              :append="true" class="dialog_cate" @close="closeCate">
              <div style="padding: 0px 20px">
                <el-form ref="form" :model="form" label-width="80px" :rules="formRules">
                  <el-form-item :label="$t('上级分类')" prop="parent_id">
                    <el-select v-model="form.parent_id">
                      <el-option v-for="item in cateList" :key="item.id" :label="item.title" :value="item.id" />
                    </el-select>
                  </el-form-item>
                  <el-form-item :label="$t('分类名称')" prop="title">
                    <el-input v-model="form.title" />
                  </el-form-item>
                  <!-- <el-form-item label="自定义文件夹" prop="path">
                    <el-input v-model="form.path" />
                  </el-form-item> -->
                </el-form>
                <div style="text-align: center" class="dialog-footer">
                  <el-button type="primary" size="larger" @click="submit">
                    {{ $t('提交') }}
                  </el-button>
                </div>
              </div>
            </BaseDialog>
          </div>
        </div>
        <div class="right" v-loading="loading">
          <AttachmentList v-if="dialogShow" ref="attachmentList" :attachment-cate="cate_id"
            :attachment-type="attachmentType" @func="getData" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import attachmentApi from '@/api/system/attachment'
import compressImg from '@/utils/compressImg'
import AttachmentList from './attachment.vue'

export default {
  components: { AttachmentList },
  props: {
    title: {
      type: String,
      default: '选择附件'
    },
    dialogShow: {
      type: Boolean,
      default: false
    },
    attachmentType: {
      default: 2
    }
  },
  data() {
    return {
      loading: false,
      myHeaders: { Authorization: `Bearer ${this.$store.getters.token}` },
      uploadData: {
        type: 2,
        attachment_cate_id: 0
      },
      currentNumber: [],
      num: 0,
      urlForm: {
        name: '',
        url: '',
        description: '',
        storage: 5
      },
      urlRules: {
        name: [
          {
            required: 'true',
            message: this.$t('请输入附件名'),
            trigger: 'blur'
          }
        ],
        url: [
          {
            required: 'true',
            message: this.$t('请输入附件地址'),
            trigger: 'blur'
          }
        ]
      },
      showDialog: false,
      show: false,
      currentNode: 0,
      defaultExpandKeys: [],
      dialogShow2: false,
      form: {
        parent_id: '',
        path: '',
        title: ''
      },
      formRules: {
        parent_id: [
          {
            required: true,
            message: this.$t('请选择上级分类'),
            trigger: 'change'
          }
        ],
        title: [
          {
            required: true,
            message: this.$t('请输入分类名称'),
            trigger: 'blur'
          }
        ]
      },
      cate_id: '',
      cateList: [],
      treeData: [],
      // data: JSON.parse(JSON.stringify(data)),
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      showTree: false, // 是否点击节点展开树，false 只能点前面三角图标展开
      showAdd: false,
      showBtn: [],
      showEdit: false,
      showDele: false,
      cateTitle: '',
      is_used: false
    }
  },
  watch: {
    treeData(val, value) { },
    dialogShow: function (val, value) {
      this.show = val
      this.dialogShow = val
      if (this.show) {
        // this.getCateList()
      }
    }
    // attachmentType(val, value) {
    //   this.attachmentType = val
    //   console.log(val, value, '附件类型')
    //   this.getCateList()
    // }
  },
  created() {
    localStorage.setItem('is_used', '')
  },
  mounted() {
    this.cate_id = 0
    this.currentNode = 0
  },
  updated() {
    const isUsed = localStorage.getItem('is_used')
    if (!isUsed) {
      localStorage.setItem('is_used', 1)
      this.cate_id = 0
      this.currentNode = 0
      this.showBtn = []
      this.showEdit = false
      this.showDele = false
      this.$set(this.showBtn, 0, true)
      this.showAdd = true
      this.getCateList()
    }
  },
  methods: {
    // 添加网络附件
    uploadUrl() {
      const val = []
      val.push(this.urlForm)
      attachmentApi.attachmentSave(val).then(res => {
        if (res.code == 0) {
          this.$message.success(res.msg)
          this.showDialog = false
          this.$refs.attachmentList.getAttachmentList()
        } else {
          this.$message.error(re.smsg)
        }
      })
    },
    // 点击上传
    getTypeCate() {
      this.uploadData.attachment_cate_id = this.cate_id
      this.uploadData.type = this.attachmentType
    },
    // 上传之前 压缩生成缩略图
    async beforeUpload(file) {
      const url = await compressImg(file, 0.2)
      this.uploadData.reduce_img = url.file
    },
    // 上传中
    onProgress() {
      this.loading = true
    },
    // 上传成功
    handleSuccess(res, file, fileList) {
      this.loading = false
      if (res.code == 0) {
        this.$refs.attachmentList.getAttachmentList(this.cate_id)
      }
    },
    // 删除附件
    dele() {
      this.$confirm(this.$t('删除该文件'), this.$t('提示'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      })
        .then(() => {
          attachmentApi
            .attachmentDelete({ id: this.currentNumber })
            .then(res => {
              if (res.code == 0) {
                this.$message.success(res.msg)
                this.$refs.attachmentList.getAttachmentList()
              }
            })
        })
        .catch(() => { })
    },
    searchCate() {
      this.getCateList(this.cateTitle)
    },
    // 附件类别
    close() {
      this.$emit('update:dialogShow', this.show)
      localStorage.setItem('is_used', '')
    },
    getCateList(val) {
      var that = this
      attachmentApi.cateList({ title: val == 0 ? '' : val }).then(res => {
        if (res.code == 0) {
          // 重新打开时 初始化到全部分类下

          if (val == 0) {
            this.currentNode = 0
            this.$set(this.showBtn, val, true)
            this.showAdd = true
            this.cate_id = val
          }
          that.treeData = res.data
          this.cateList = JSON.parse(JSON.stringify(res.data))
          this.cateList[0].title = '一级分类'
          this.defaultExpandKeys = [this.currentNode]
          this.$nextTick(() => {
            // console.log(this.currentNode, '-----------')
            // this.$refs.tree.setCurrentKey(this.currentNode)
            // this.$refs.attachmentList.getAttachmentList(this.cate_id)
          })
        }
      })
    },
    // 点击分类
    handleNodeClick(data) {
      this.currentNode = data.id
      this.cate_id = data.id
      // 调用父组件的方法请求附件列表
      // this.$emit('update', data.id)
      this.$refs.attachmentList.getAttachmentList(data.id)
      // 判断是否显示新增用户按钮
      if (data.parent_id == 0) {
        this.showAdd = true
      } else {
        this.showAdd = false
      }
      // 展示增删改icon
      if (data.id == 0) {
        this.showEdit = false
        this.showDele = false
      } else {
        this.showEdit = true
        this.showDele = true
      }
      this.showBtn = []
      this.$set(this.showBtn, data.id, true)
    },
    // 新增分类
    append(data) {
      this.dialogShow2 = true
      this.cate_id = ''
      this.form.parent_id = data.id
      this.form.title = ''
    },
    // 编辑分类
    edit(data) {
      // console.log(data, '------------------')
      this.dialogShow2 = true
      this.form.parent_id = data.parent_id
      this.form.title = data.title
      this.cate_id = data.id
    },
    // 关闭分类
    closeCate() {
      this.dialogShow2 = false
    },
    // 删除分类
    remove(data) {
      // console.log(data)
      // return
      this.$confirm(this.$t('删除该分类'), this.$t('提示'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      })
        .then(() => {
          attachmentApi.cateDelete({ id: [data.id] }).then(res => {
            if (res.code == 0) {
              this.$message.success(res.msg)
              this.getCateList()
            }
          })
        })
        .catch(() => { })
    },
    // 提交编辑、新增分类
    submit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (!this.cate_id) {
            attachmentApi.cateSave({ ...this.form }).then(res => {
              if (res.code == 0) {
                this.dialogShow = false
                this.$message.success(res.msg)
                this.getCateList()
              }
            })
          } else {
            const val = this.form
            val.id = this.cate_id
            attachmentApi.cateUpdate(val).then(res => {
              if (res.code == 0) {
                this.dialogShow = false
                this.$message.success(res.msg)
                this.getCateList()
              }
            })
          }
        } else {
          this.$message.error(this.$t('请填写必要信息'))
        }
      })
    },
    choose() {
      this.$emit('func', this.currentItem)
      // console.log(this.currentItem)
    },
    // 往父组件传值
    getData(num, currentItem) {
      this.num = num
      this.currentItem = currentItem
      // this.$emit('func', this.currentItem)
      // console.log(val)
    }
  }
}
</script>
<style lang="scss">
.dialog_cate {
  .el-select {
    width: 100%;
  }

  .el-button--primary {
    background-color: var(--huocms-com-color-primary);
    border-color: var(--huocms-com-color-primary);
    border-radius: 30px;
  }

  .el-button--primary:hover,
  .el-button--primary:focus {
    background-color: var(--huocms-com-color-primary);
    border-color: var(--huocms-com-color-primary);
  }
}

#attachment {
  .el-button.is-plain {
    border: solid 1px var(--huocms-com-color-primary);
    color: var(--huocms-com-color-primary);
  }
}

#attachmentCate {
  height: 400px;

  .allCate {
    height: 30px;
  }

  .el-scrollbar {
    height: 100%;
  }

  .el-scrollbar__thumb {
    width: 0;
  }

  .el-scrollbar__wrap {
    overflow-x: hidden;
  }

  // 添加部门时设置菜单
  .el-tree.form-tree {
    padding: 10px 20px;
  }

  .el-tree {
    padding: 20px 0;
    font-size: 14px;
  }

  .treelistCont {
    width: 500px;
  }

  /* 高亮显示选中 */
  .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
    color: var(--huocms-com-color-primary);
    background-color: rgba(255, 125, 0, 0.06);
    border-radius: 6px;

    .el-tree-node__expand-icon {
      color: var(--huocms-com-color-primary);
    }

    .el-tree-node__expand-icon.is-leaf {
      color: transparent;
    }
  }

  .el-tree-node__content {
    height: 40px;
    line-height: 20px;
  }

  .el-tree-node__content .el-input {
    width: auto;
    min-width: 60px;
  }

  .treeSortList {
    width: calc(100% - 28px);
    align-items: center;
    justify-content: space-between;
    position: relative;
    display: flex;

    .tooltip-wrap {
      width: calc(100% - 68px);
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  .treeSortList .doBtn {
    width: 62px;
    z-index: 999;
    text-align: right;

    .el-button--mini {
      padding: 0;
    }
  }

  .treeSortList .doBtn .el-button--text {
    color: var(--huocms-com-color-primary);
  }

  .treeSortList .doBtn .el-button--text i.el-icon-delete {
    color: #f77501;
  }

  .treeSortList .doBtn .el-button--text i.el-icon-plus {
    color: var(--huocms-com-color-primary);
  }

  .treeSortList .doBtn .el-button--text i.el-icon-edit-outline {
    color: var(--huocms-com-color-primary);
  }

  .treeSortList .doBtn .el-button--text i.el-icon-setting {
    color: var(--huocms-com-color-primary);
  }
}
</style>
<style scoped lang="scss">
.top-flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-right: 16px;

  .left {
    flex: 1;
    display: flex;

    .el-button {
      margin-right: 8px;
    }
  }
}

.content {
  display: flex;
  border: solid 1px #eee;
  margin-top: 8px;

  .left {
    width: 225px;
    padding-top: 16px;

    .search-input {
      padding: 0 8px;
    }
  }

  .right {
    width: calc(100% - 220px);
    border-left: solid 1px #eee;
  }
}
</style>
